package com.example.socketdemo.buffer.three;

import java.io.*;
import java.net.Socket;

/**
 * socket 线程
 */
public class SocketThread extends Thread{

    private Socket socket;

    public SocketThread(Socket socket){
        this.socket = socket;
    }

    @Override
    public void run(){
        try {
            // 3. 从Socket管道中得到一个字节输入流。
            InputStream is = socket.getInputStream();
            // 4. 把字节输入流包装成自己需要的流进行数据的读取。
            BufferedReader br = new BufferedReader(new InputStreamReader(is));

            String line;
            while((line = br.readLine()) != null){
                System.out.println(line);

                sendMessage(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            ServerSocketTest.allSocket.remove(socket);
        }
    }

    /**
     * 发送消息到各客户端
     * @param line
     */
    private void sendMessage(String line) {

        for (Socket so : ServerSocketTest.allSocket) {
            try {
                PrintStream pw = new PrintStream(so.getOutputStream());
                pw.println(line);

                pw.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}
